import { createApp } from 'vue'
import App from './App.vue'

import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';
import {createRouter,createWebHashHistory} from 'vue-router'
import Axios from 'axios'
import Main from './components/Main.vue'
import UserList from './components/UserList.vue'
import Login from './components/Login.vue'
import { createStore } from 'vuex'

// 创建一个新的 store 实例
const store = createStore({
    state () {
        return {
            count: 0,
            myCollapse:false,
            userInfo:'匿名用户'
        }
    },
    mutations: {
        openMenu(state){
            state.myCollapse = false;
        },
            closeMenu(state){
            state.myCollapse = true;
        },
        increment (state) {
            state.count++
        },
        initUserInfo(state) {
            debugger
            let jwt = require('jsonwebtoken')
            let secret = "Q12@3$fas3@!"
            let token = window.sessionStorage.getItem('token')
            if(token){
                jwt.verify(token,secret,(err,decode)=>{     //验证token
                    if(err){
                        return err
                    }else{
                        debugger
                        state.userInfo = decode.username
                    }
                })
            }else{
                state.userInfo = '匿名用户'
            }
        }
    }
})

// 1. 定义路由组件.
// 也可以从其他文件导入
const AddPro = { template: '<div>添加商品</div>' }

// 2. 定义一些路由
const routes = [
    { path: '/login', component: Login },
    { path: '/', redirect: {path:'/login'} },
    { path: '/main', component: Main },
    { path: '/userList', component: UserList },
    { path: '/addPro', component: AddPro },
]
const router = createRouter({
    // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    history: createWebHashHistory(),
    routes, // `routes: routes` 的缩写
})

router.beforeEach((to, from, next) => {
    debugger
    if(to.path == '/login'){
        return next()
    }
    //如果没有session
    const tokenStr = window.sessionStorage.getItem("token")
    if(!tokenStr){
        $
        return next('/login')
    }
    //设置jwttoken
    console.log(to)
    console.log(from)
    next()
})

// http request 拦截器
Axios.interceptors.request.use(
    config => {
        debugger
        let token = sessionStorage.getItem('token');
        if (token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
            token =sessionStorage.getItem('token')+':';
            config.headers['token'] = token;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    });


const app = createApp(App)
app.config.globalProperties.$axios=Axios //全局配置axios
app.use(ElementPlus)
app.use(router)
app.use(store)
app.mount('#app')
